package com.zkq.graduate.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Strings;
import com.zkq.graduate.annotation.Admin;
import com.zkq.graduate.enums.ResponseEnum;
import com.zkq.graduate.pojo.SystemTime;
import com.zkq.graduate.service.*;
import com.zkq.graduate.util.ImportExeclUtil;
import com.zkq.graduate.util.ResultHandler;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @Author zhangkaiqiang
 * @Date 2019/12/24  16:51
 * @Description TODO
 */
@RestController
@RequestMapping("/api/v1/admin")
@Api(tags = {"教务管理员模块"},description = "教务管理员相关接口")
public class AdminController {


	@Resource(name = "systemTimeService")
	private SystemTimeService systemTimeService;


	@Resource(name = "studentService")
	private StudentService studentService;

	@Resource(name = "userService")
	private UserService userService;

	@Resource(name = "userAndRoleService")
	private UserAndRoleService userAndRoleService;


	@Resource(name = "teacherService")
	private TeacherService teacherService;


	@Admin
	@PostMapping("/time")
	@ApiOperation(value = "新增时间范围记录",notes = "每年的选题、开题报告等都在特定时间内才允许执行操作")
	public ResultHandler<String> insertOneRecord(SystemTime systemTime){
		if(systemTimeService.insertOneRecord(systemTime)){
			return ResultHandler.success();
		}
		return ResultHandler.fail(ResponseEnum.INSERT_ERROR);
	}


	@Admin
	@GetMapping("/times")
	@ApiOperation(value = "分页查看所有已经设定的时间范围")
	public ResultHandler<Page> findAll(
			@RequestParam("page") int currentPage,
			@RequestParam("limit") int pageSize){

		PageHelper.startPage(currentPage,pageSize);
		List<SystemTime> list=systemTimeService.findAll();
		PageInfo<SystemTime> pageInfo=new PageInfo<>(list);
		return ResultHandler.success(pageInfo);
	}


	@Admin
	@GetMapping("/time/{id}")
	@ApiOperation(value = "查看某个设定的时间范围的详情")
	public ResultHandler<SystemTime> findById(@PathVariable("id") int id){
		Optional<SystemTime> systemTime=systemTimeService.findById(id);
		if(systemTime.isPresent()){
			return ResultHandler.success(systemTime.get());
		}
		return ResultHandler.fail(ResponseEnum.SELECT_ERROR);
	}



	@Admin
	@DeleteMapping("/time/{ids}")
	@ApiOperation(value = "删除某个已经设定的时间范围",notes = "该接口支持单个删除与批量删除")
	public ResultHandler<String> deleteById(@PathVariable("ids") String id){
		if(!Strings.isNullOrEmpty(id)){
			String[] ids=id.split(",");
			if(systemTimeService.deleteByIds(ids)){
				return ResultHandler.success();
			}
		}
		return ResultHandler.fail(ResponseEnum.DELETE_ERROR);
	}

	@Admin
	@PatchMapping("/time")
	@ApiOperation(value = "根据id对某个时间范围进行更新")
	public ResultHandler<String> updateById(SystemTime systemTime){
			if(systemTimeService.updateById(systemTime)){
				return ResultHandler.success();
			}
		return ResultHandler.fail(ResponseEnum.UPDATE_ERROR);
	}



	@Admin
	@PostMapping("/students")
	@ApiOperation(value = "导入学生信息",notes = "插入学生信息时需要写入学生信息表、用户表、用户角色表,使用事务进行控制,某个表插入失败时进行事务的回滚操作")
	@Transactional(rollbackFor = Exception.class)
	public Map<String,Object> importStudent(MultipartFile file){

		// 进行上传的文件的校验
		Map<String,Object> checkResult=ImportExeclUtil.checkFile(file);
		if((Integer)checkResult.get("code")!=0){
			return checkResult;
		}

		// 文件导入--读取到文件中的原始数据
		Map<String,Object> resultMap=new HashMap<>();
		XSSFSheet sheet= ImportExeclUtil.getSheet(0,file);
		List<Map<String,String>> data= ImportExeclUtil.getSheetData(sheet);

		// 进行数据处理,完成某些字段名称到id的转变
		data=ImportExeclUtil.nameToValue(data,"student");

		//进行数据的插入--插入学生表、用户表、用户-角色关联表
		if(studentService.batchInsert(data)){
			if(userService.batchInsertUser(data)){
				if(userAndRoleService.batchInsert(data)){
					resultMap.put("code",0);
					resultMap.put("msg","导入学生数据成功");
				}
			}
		} else {
			resultMap.put("code",500);
			resultMap.put("msg","插入失败");
		}
		return resultMap;
	}


	/**
	 * 导入教师信息
	 * @return
	 */
	@Admin
	@PostMapping("/teachers")
	@ApiOperation(value = "导入教师信息",notes = "插入教师信息时需要写入教师信息表、用户表、用户角色表,使用事务进行控制,某个表插入失败时进行事务的回滚操作")
	@Transactional(rollbackFor = Exception.class)
	public Map<String,Object> importTeacher(MultipartFile file){

		// 进行上传的文件的校验
		Map<String,Object> checkResult=ImportExeclUtil.checkFile(file);
		if((Integer)checkResult.get("code")!=0){
			return checkResult;
		}

		// 文件导入--读取到文件中的原始数据
		Map<String,Object> resultMap=new HashMap<>();
		XSSFSheet sheet= ImportExeclUtil.getSheet(0,file);
		List<Map<String,String>> data= ImportExeclUtil.getSheetData(sheet);

		// 进行数据处理,完成某些字段名称到id的转变
		data=ImportExeclUtil.nameToValue(data,"teacher");

		//进行数据的插入--插入学生表、用户表、用户-角色关联表
		if(teacherService.batchInsertTeacher(data)){
			if(userService.batchInsertUser(data)){
				if(userAndRoleService.batchInsert(data)){
					resultMap.put("code",0);
					resultMap.put("msg","导入学生数据成功");
				}
			}
		} else {
			resultMap.put("code",500);
			resultMap.put("msg","插入失败");
		}
		return resultMap;

	}
}
